import React, { useEffect, useMemo, useState } from 'react';
import { Space, Table, Tag, Modal, Tree, Button, Cascader } from 'antd';
import '../styles/index.css';
import axios from '../axios';
export default function userManage() {
  const [content, setContent] = useState('新建员工');
  // 岗位信息
  const [rolelist, setRolelist] = useState([]);
  const getRolelist = async () => {
    let {
      data: { data },
    } = await axios.get('/getRolelist');
    setRolelist(data);
  };
  useEffect(() => {
    getRolelist();
  }, []);

  // 搜索栏
  const [sflag, setSflag] = useState(false);
  const [susername, setSusername] = useState('');
  const [srole, setSrole] = useState('');

  // 添加框 && 编辑
  const [_id, setId] = useState('');
  const [ogrrole, setOgrrole] = useState([]);
  const getOgrRole = async () => {
    let {
      data: { data },
    } = await axios.get('/getOgrRole');
    let arr: any = [];
    data
      .filter((item: any) => {
        const _id = ogr.split(',')[0];
        setOrg(ogr.split(',')[1]);
        setOid(_id);
        return item.pid === _id;
      })
      .forEach((item: any) => {
        arr.push({
          value: item._id,
          label: item.name,
          children: item.roles.map((ele: any) => {
            return {
              value: ele._id,
              label: ele.name,
            };
          }),
        });
      });
    setOgrrole(arr);
  };

  const onChange = (value: any) => {
    setPartid(value[0]);
    setRid(value[1]);
  };

  const [modal1Open, setModal1Open] = useState(false);
  const [modal2Open, setModal2Open] = useState(false);
  const [ogr, setOgr] = useState('');
  const [org, setOrg] = useState('');
  const [rid, setRid] = useState('');
  // const [part, setPart] = useState('')
  const [partid, setPartid] = useState('');
  const [company, setCompany] = useState([]);
  const [role, setRole] = useState('6659baf739bf707f632b6eb4');
  const [card, setCard] = useState('');
  const [phone, setPhone] = useState('');
  const [username, setName] = useState('');
  const [desc, setDesc] = useState('');
  const [type, setType] = useState('');
  const [oid, setOid] = useState('');
  const [flag, setFlag] = useState(false);
  const adduser = async () => {
    if (_id) {
      let data = await axios.post('/updateuser', {
        _id,
        username,
        card,
        phone,
        roles: role,
        org,
        rid,
        // part,
        desc,
        type,
        oid,
        partid,
      });
      setName('');
      setDesc('');
      setCard('');
      setPhone('');
      setOgr('');
      setFlag(!flag);
      setId('');
    }
    if (!_id) {
      let data = await axios.post('/addUser', {
        username,
        card,
        phone,
        roles: role,
        org,
        rid,
        // part,
        desc,
        type,
        oid,
        partid,
      });
      setName('');
      setDesc('');
      setCard('');
      setPhone('');
      setOgr('');
      setFlag(!flag);
    }
  };
  const [sleft, setSleft] = useState('');
  const onSelect = (selectedKeys: any, info: any) => {
    // console.log('selected', selectedKeys, info);
    setSleft(selectedKeys);
    // console.log(sleft+'123')
  };

  const [treeData, settreeDatas] = useState([]);
  const [treeOrganization, setTreeOrganization] = useState([]);
  const getTreeOrganization = async () => {
    let {
      data: { data, company },
    } = await axios.get('/getTreeOrganization');
    setTreeOrganization(data);
    setCompany(company);

    let datalist: any = [];
    data.map((item: any, index: number) => {
      datalist.push({
        title: item.name,
        key: item._id,
        children: item.children.map((item: any, index: number) => {
          return {
            title: item.name,
            key: item._id,
            children: item.children.map((item: any, index: number) => {
              return {
                title: item.name,
                key: item._id,
              };
            }),
          };
        }),
      });
    });
    settreeDatas(datalist);
  };

  useEffect(() => {
    getTreeOrganization();
  }, []);
  useEffect(() => {
    getOgrRole();
  }, [ogr]);
  // 表格
  const columns = [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'order',
    },
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username',
    },
    // {
    //   title: '公司',
    //   dataIndex: 'org',
    //   key: 'org',
    // },
    // {
    //   title: '部门',
    //   dataIndex: 'part',
    //   key: 'part',
    // },
    {
      title: '岗位',
      dataIndex: 'roles',
      key: 'roles',
    },
    {
      title: '工号',
      dataIndex: 'card',
      key: 'card',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },

    {
      title: '修改时间',
      dataIndex: 'changetime',
      key: 'changetime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: any) => (
        <div>
          {status === true ? (
            <span style={{ color: 'green' }}>已启用</span>
          ) : (
            <span style={{ color: 'red' }}>已禁用</span>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (status: any) => {
        return (
          <div>
            <span className="hwy-edit">编辑</span>
            <span className="hwy-edit">删除</span>
            {status === true ? (
              <span className="hwy-edit">禁用</span>
            ) : (
              <span className="hwy-edit">启用</span>
            )}
          </div>
        );
      },
    },
  ];
  const [user, setUser] = useState([]);

  const getuserrole = async () => {
    let {
      data: { data },
    } = await axios.get('/getuserrole');
    const datas = data.filter((item: any) => {
      return item.role === '6659baf739bf707f632b6eb4';
    });
    setUser(datas);
  };
  const [datas, setDatas] = useState([]);

  useMemo(() => {
    let arr = [...user];
    if (susername) {
      arr = arr.filter((item: any) => item.username.includes(susername));
    }
    if (srole) {
      arr = arr.filter((item: any) => {
        if (item.rid != null) {
          return item.rid.name === srole;
        }
      });
    }
    if (sleft) {
      console.log(arr);
      console.log(sleft);

      arr = arr.filter((item: any) => {
        if (item.partid == null) return item.oid._id === sleft[0];
        else {
          return item.oid._id === sleft[0] || item.partid._id === sleft[0];
        }
      });
    }
    let lists: any = [];
    arr.map((item: any, index: number) => {
      if (item.rid === null) {
        lists.push({
          order: index + 1,
          username: item.username,
          // org: item.oid.name,
          // part: item.partid.name,
          roles: '暂无',
          card: item.card,
          phone: item.phone,
          changetime: item.changetime.split('T')[0],
          status: item.status,
          operation: item.status,
          _id: item._id,
          type: item.type,
        });
      } else {
        lists.push({
          order: index + 1,
          username: item.username,
          // org: item.oid.name,
          // part: item.partid.name,
          roles: item.rid.name,
          card: item.card,
          phone: item.phone,
          changetime: item.changetime.split('T')[0],
          status: item.status,
          operation: item.status,
          _id: item._id,
          type: item.type,
        });
      }
    });
    setDatas(lists);
  }, [sflag, user]);

  // 删除员工
  const deleteUser = async (_id: any) => {
    setFlag(!flag);
    let {
      data: { data },
    } = await axios.post('/deleteuser', { _id });
  };

  // 启用禁用员工
  const changeStatus = async (_id: any, status: any) => {
    setFlag(!flag);
    let {
      data: { data },
    } = await axios.post('/changeuserstatus', { _id, status });
  };

  useEffect(() => {
    getuserrole();
  }, [flag]);

  return (
    <div className="hwy-userManage">
      <div className="hwy-userManage-left">
        <p>组织机构</p>
        <Tree
          showLine
          defaultExpandedKeys={['0-0-0']}
          onSelect={onSelect}
          treeData={treeData}
        />
      </div>

      <div>
        <div className="hwy-search-box">
          <div>
            <span>姓名：</span>
            <input
              type="text"
              placeholder="输入姓名"
              value={susername}
              onChange={(e) => {
                setSusername(e.target.value);
              }}
            />
          </div>
          <div>
            <span className="hwy-search-sp">岗位：</span>
            <select
              className="hwy-search-select"
              value={srole}
              onChange={(e) => {
                setSrole(e.target.value);
              }}
            >
              <option value="">请选择</option>
              {rolelist.map((item: any, index: number) => {
                return (
                  <option key={index} value={item.name}>
                    {item.name}
                  </option>
                );
              })}
            </select>
          </div>

          <div>
            <Button
              className="hwy-search-btn1"
              type="primary"
              onClick={() => setSflag(!sflag)}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                setSusername(''), setSrole('');
                setSleft('');
              }}
            >
              重置
            </Button>
          </div>
        </div>

        <div className="hwy-table-box">
          <div className="hwy-add-box">
            <button
              className="hwy-add-btn1"
              onClick={() => {
                setContent('添加员工');
                setModal2Open(true);
              }}
            >
              添加员工
            </button>
            <div>
              <button className="hwy-add-btn2">导入</button>
              <button className="hwy-add-btn1">导出</button>
            </div>
          </div>
          <Table
            columns={columns}
            dataSource={datas}
            pagination={{
              showTotal: (total, range) => `共${total}条`,
              pageSizeOptions: ['5', '10', '15', '20'],
              showSizeChanger: true,
            }}
            onRow={(record: any) => {
              return {
                onClick: (event: any) => {
                  if (
                    event.target.innerText === '禁用' ||
                    event.target.innerText === '启用'
                  ) {
                    changeStatus(record._id, !record.status);
                    console.log(!record.status);
                  }
                  if (event.target.innerText === '编辑') {
                    console.log(_id);
                    setContent('编辑');
                    setId(record._id);
                    setName(record.username);
                    setType(record.type);
                    setCard(record.card);
                    setPhone(record.phone);
                    // setOgr(record.oid)
                    setRole(record.rid);
                    setType(record.type);
                    setDesc(record.desc);
                    setModal2Open(true);
                  }
                  if (event.target.innerText === '删除') {
                    deleteUser(record._id);
                  }
                },
              };
            }}
          />

          <div>
            <Modal
              title={content}
              centered
              open={modal2Open}
              onOk={() => {
                setModal2Open(false);
                adduser();
              }}
              onCancel={() => {
                setModal2Open(false);
              }}
            >
              <div className="hwy-userManage-modal">
                员工姓名：
                <input
                  type="text"
                  placeholder="输入员工姓名"
                  value={username}
                  onChange={(e) => {
                    setName(e.target.value);
                  }}
                />
                <br />
                员工电话：
                <input
                  type="text"
                  placeholder="输入员工电话"
                  value={phone}
                  onChange={(e: any) => {
                    setPhone(e.target.value);
                  }}
                />
                <br />
                员工编号：
                <input
                  type="text"
                  placeholder="输入员工编号"
                  value={card}
                  onChange={(e: any) => {
                    setCard(e.target.value);
                  }}
                />
                <br />
                公司：
                <select
                  name=""
                  id=""
                  value={ogr}
                  onChange={(e: any) => {
                    setOgr(e.target.value);
                  }}
                >
                  {company.map((item: any, index: number) => {
                    return (
                      <option value={[item._id, item.name]} key={index}>
                        {item.name}
                      </option>
                    );
                  })}
                </select>
                <br />
                部门/职位：{' '}
                <Cascader
                  options={ogrrole}
                  onChange={onChange}
                  placeholder="Please select"
                />
                <br />
                <br />
                类型：
                <select
                  name=""
                  id=""
                  value={type}
                  onChange={(e) => {
                    setType(e.target.value);
                  }}
                >
                  <option value="">请选择</option>
                  <option value="正式员工">正式员工</option>
                  <option value="实习员工">实习员工</option>
                  <option value="外包员工">外包员工</option>
                </select>
                <br />
                描述：
                <textarea
                  value={desc}
                  onChange={(e) => {
                    setDesc(e.target.value);
                  }}
                ></textarea>
                <br />
              </div>
            </Modal>
          </div>
          <div></div>
        </div>
      </div>
    </div>
  );
}
